import typing as T
from fastapi import Depends
from sqlmodel import select, update, insert, delete, and_, desc

from ...init.Global import Session
from ...pojo import User2Session, User2SessionVO

# 用户会话相关操作的Mapper[对外]


class _UserSessionMapper:

    session: Session = None

    def __call__(self, session: Session):
        self.session = session
        return self

    async def createSession(self, entity: User2Session):
        self.session.add(entity)

    # 根据用户id查询会话信息的功能(先不考虑分页)
    async def getSessionByUserId(self, userId: int):
        result = (
            (
                await self.session.execute(
                    select(User2Session)
                    .where(User2Session.userId == userId)
                    .order_by(desc(User2Session.createTime))
                )
            )
            .scalars()
            .all()
        )
        return [User2SessionVO(**item.model_dump()) for item in result]

    # 根据会话id改名的功能
    async def updateSessionNameBySessionId(self, sessionId: int, name: str):
        await self.session.execute(
            update(User2Session).values(alias=name).where(User2Session.id == sessionId)
        )

    # 根据会话id删除会话信息的功能
    async def deleteSessionById(self, sessionId: int):
        await self.session.execute(
            delete(User2Session).where(User2Session.id == sessionId)
        )


UserSessionMapper = T.Annotated[_UserSessionMapper, Depends(_UserSessionMapper())]
